package com.itfetter.trade.listener;

import com.itfetter.api.client.PayClient;
import com.itfetter.api.dto.PayOrderDto;
import com.itfetter.trade.domain.dto.OrderFormDTO;
import com.itfetter.trade.domain.po.Order;
import com.itfetter.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
@RocketMQMessageListener(topic = "pay-delay", consumerGroup = "rocketmq-consumer-trade")
public class PayDelayListener implements RocketMQListener<Message> {
    private final PayClient payClient;
    private final IOrderService orderService;
    private final RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Message message) {
        //获取消息头部中的信息，业务订单id
        Long bizOrderNo = (Long) message.getHeaders().get("bizOrderNo");
        //获取下一次发延迟消息的等级
        int nextDelay = (int) message.getPayload();
        //根据订单id获取订单
        Order order = orderService.getById(bizOrderNo);
        //查询获取的订单是否存在或订单是否已支付或关闭
        if (order == null || order.getStatus() > 1) {
            //订单不存在或交易已关闭，不处理
            return;
        }
        //根据订单id查询订单支付状态
        PayOrderDto payOrderDto = payClient.queryPayOrderByBizOrderNo(bizOrderNo);
        //支付单存在，且支付单已支付
        if (payOrderDto != null && payOrderDto.getStatus() == 3) {
            //修改订单状态为已支付
            orderService.markOrderPaySuccess(bizOrderNo);
            return;
        }
        //判断当前延迟等级，超过16，就是超过了30分钟
        if (nextDelay <= 16) {
            //没超过30分钟，继续发送延迟消息
            Map<String,Object> map=new HashMap<>();
            map.put("bizOrderNo",order.getId());
            Message message1= MessageBuilder.createMessage((nextDelay+1),new MessageHeaders(map));

            rocketMQTemplate.syncSend("pay-delay",message1,1000,(nextDelay+1));
            return;
        }
        //订单超过了30分钟，取消订单
        orderService.cancelOrder(order.getId());

    }
}
